package com.xhdx.threadpool.tools;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 特点： 一定要等双方将数据都拿出来后才能交换(只能是两个线程)
 * 
 *
 */
public class ExchangerTest {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        Exchanger<String> exchanger = new Exchanger<String>();

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + ":交换数据：" + Thread.currentThread().getName());
                try {
                    String getDate = exchanger.exchange(Thread.currentThread().getName());
                    System.out.println(Thread.currentThread().getName() + ":收到数据：" + getDate);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "交换数据：" + Thread.currentThread().getName());
                try {
                    String getDate = exchanger.exchange(Thread.currentThread().getName());
                    System.out.println(Thread.currentThread().getName() + "收到数据：" + getDate);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        threadPool.shutdown();
    }
}